package com.lmabbe.common.datasources.plugin;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.ds.GroupDataSource;
import com.baomidou.dynamic.datasource.support.DdConstants;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.dynamic.datasource.toolkit.StringUtils;
import com.lmabbe.common.global.constant.GlobalConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author lmabbe
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Slf4j
@RequiredArgsConstructor
public class TenantMasterSlaveAutoRoutingPlugin implements Interceptor {

    private static final AtomicInteger master = new AtomicInteger(0);
    private static final AtomicInteger slave = new AtomicInteger(0);
    private final ApplicationContext applicationContext;
    public static ThreadLocal<RpcContext> rpcContextThreadLocal = new ThreadLocal<>();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        DynamicRoutingDataSource bean = applicationContext.getBean(DynamicRoutingDataSource.class);
        Map<String, GroupDataSource> currentGroupDataSources = bean.getCurrentGroupDataSources();
        String tenantId = RpcContext.getContext().getAttachment(GlobalConstant.SYSTEM.TENANT_ID);

        //租户ID为空，就是创建表
        if (StringUtils.isBlank(tenantId)) {
            return invocation.proceed();
        }

        GroupDataSource groupDataSource = currentGroupDataSources.get(tenantId);
        if (groupDataSource.getDataSourceMap().size() == 1) {
            Set<String> strings = groupDataSource.getDataSourceMap().keySet();
            String next = strings.iterator().next();
            DynamicDataSourceContextHolder.push(next);
        } else {
            MappedStatement mappedStatement = (MappedStatement) args[0];
            String currentDataSource = SqlCommandType.SELECT == mappedStatement.getSqlCommandType() ? DdConstants.SLAVE : DdConstants.MASTER;
            List<String> collect = groupDataSource.getDataSourceMap().keySet().stream().filter(s -> s.contains(currentDataSource)).collect(Collectors.toList());
            String ds = "";
            if (currentDataSource.equals(DdConstants.SLAVE)) {
                ds = collect.get(Math.abs(slave.getAndAdd(1) % collect.size()));
            } else {
                ds = collect.get(Math.abs(master.getAndAdd(1) % collect.size()));
            }
            DynamicDataSourceContextHolder.push(ds);
        }
        return invocation.proceed();

    }

    @Override
    public Object plugin(Object target) {
        return target instanceof Executor ? Plugin.wrap(target, this) : target;
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
